/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "cJSON.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "nfc_kits.h"
#include "wifi_device.h"
#include "wifi_sta.h"


static WifiInfo ReadWifiInfoFromNfcTags(void) {
    NfcI2cInit();
    osDelay(10);

    WifiInfo m_wifiInfo = {0};

    for (;;) {

        NdefParsingList *head = NfcTagRead();

        unsigned char nfc_content[NDEF_RECORD_SIZE] = {0};

        NdefParsingList *node = head->next;
        if (head != NULL && node != NULL) {
            memset(nfc_content, '\0', sizeof(nfc_content));
            memcpy(nfc_content, node->ndef.payload, node->ndef.payloadLen);

            printf("nfctag: %s \r\n", nfc_content);

            cJSON *cjson = cJSON_Parse(nfc_content);
            if (cjson != NULL) {
                cJSON *ssidItem = cJSON_GetObjectItem(cjson, "ssid");
                if (ssidItem != NULL) {
                    char *c_ssid = cJSON_GetStringValue(ssidItem);
                    memcpy(m_wifiInfo.ssid, c_ssid, strlen(c_ssid));
                }

                cJSON *pwdItem = cJSON_GetObjectItem(cjson, "pwd");
                if (pwdItem != NULL) {
                    char *c_password = cJSON_GetStringValue(pwdItem);
                    memcpy(m_wifiInfo.password, c_password, strlen(c_password));
                }
            } 
        }

        NfcReadTagFree(head);

        if (m_wifiInfo.ssid != NULL && strlen(m_wifiInfo.ssid) > 0) {
            break;
        }

        osDelay(200);
    }

    return m_wifiInfo;
}

static void *WifiNfcThreadTask(void) {

    WifiInfo m_wifiInfo = ReadWifiInfoFromNfcTags();

    printf("wifi ssid: %s , password: %s \r\n", m_wifiInfo.ssid, m_wifiInfo.password);

    WifiConnect(m_wifiInfo);
}

static void WifiNfcExample(void) {
    printf("\nentry wifi nfc example.\r\n");

    osThreadAttr_t attr;

    attr.name = "WifiNfcExample";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)WifiNfcThreadTask, NULL, &attr) == NULL) {
        printf("Falied to create WifiNfcThreadTask!\n");
    }
}

APP_FEATURE_INIT(WifiNfcExample);
